package chatdialogservicelogic

import (
	"context"
	"time"

	dialogmodel "paper-pro/app/chat/model/chatdialog"
	"paper-pro/app/chat/rpc/internal/svc"
	"paper-pro/app/chat/rpc/pb"
	assistantclient "paper-pro/pkg/rpc/assistant"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *pb.ChatDialogCreateReq) (*pb.ChatDialogCreateResp, error) {
	_, err := l.svcCtx.AssistantRpc.GetAssistant(l.ctx, &assistantclient.GetAssistantReq{
		Id:     in.Dialog.AssistantId,
		UserId: in.Dialog.UserId,
	})
	if err != nil {
		return nil, errors.Wrapf(err, "Create Chat Dialog: 校验 Assistant Id: %s 失败: %v", in.Dialog.AssistantId, err)
	}

	oAssistantId, err := primitive.ObjectIDFromHex(in.Dialog.AssistantId)
	if err != nil {
		return nil, errors.Wrap(err, "Create Chat Dialog: failed, When get Object AssistantId")
	}
	// todo: 创建前需先获取Assistant确保其存在
	newDialog := dialogmodel.ChatDialog{
		Name:         in.Dialog.Name,
		LastActiveAt: time.Now(),
		AssistantId:  oAssistantId,
		UserId:       in.Dialog.UserId,
		RequestId:    in.Dialog.RequestId,
	}
	err = l.svcCtx.ChatDialogModel.Insert(l.ctx, &newDialog)
	if err != nil {
		return nil, errors.Wrap(err, "Create Chat Dialog: failed")
	}

	return &pb.ChatDialogCreateResp{
		Dialog: &pb.ChatDialog{
			Id:           newDialog.ID.Hex(),
			UpdateAt:     newDialog.UpdateAt.Unix(),
			CreateAt:     newDialog.CreateAt.Unix(),
			Name:         newDialog.Name,
			LastActiveAt: newDialog.LastActiveAt.Unix(),
			AssistantId:  newDialog.AssistantId.Hex(),
			UserId:       newDialog.UserId,
		},
	}, nil
}
